// 消息存储相关功能

import type { Message } from './chat-types';
import { storageSet, storageGet, isTauri } from '../services/secure-storage';
import { Ref } from 'vue';

/**
 * 获取已删除消息ID列表的存储键名
 */
async function getDeletedMessagesStorageKey(currentUserId: Ref<string | null>): Promise<string> {
  let userId = isTauri()
    ? await storageGet('openId')
    : localStorage.getItem('openId');
  
  if (!userId && currentUserId.value) {
    userId = currentUserId.value;
  }
  
  if (!userId) {
    throw new Error('无法获取当前用户的 open_id，请先登录后再读取已删除消息列表');
  }
  
  return `deleted_message_ids_${userId}`;
}

/**
 * 获取已删除的消息ID列表
 */
export async function getDeletedMessageIds(currentUserId: Ref<string | null>): Promise<Set<string>> {
  try {
    const storageKey = await getDeletedMessagesStorageKey(currentUserId);
    const deleted = await storageGet(storageKey);
    if (deleted) {
      const ids = JSON.parse(deleted);
      return new Set(Array.isArray(ids) ? ids : []);
    }
    return new Set<string>();
  } catch (error) {
    console.error('获取已删除消息ID列表失败:', error);
    return new Set<string>();
  }
}

/**
 * 保存已删除的消息ID列表
 */
export async function saveDeletedMessageIds(
  deletedIds: Set<string>,
  currentUserId: Ref<string | null>
): Promise<void> {
  try {
    const storageKey = await getDeletedMessagesStorageKey(currentUserId);
    const ids = Array.from(deletedIds);
    const value = JSON.stringify(ids);
    
    if (isTauri()) {
      await storageSet(storageKey, value);
    } else {
      localStorage.setItem(storageKey, value);
    }
  } catch (error) {
    console.error('保存已删除消息ID列表失败:', error);
  }
}

/**
 * 添加消息ID到已删除列表
 */
export async function addDeletedMessageId(
  messageId: string,
  currentUserId: Ref<string | null>
): Promise<void> {
  const deletedIds = await getDeletedMessageIds(currentUserId);
  deletedIds.add(messageId);
  await saveDeletedMessageIds(deletedIds, currentUserId);
}

/**
 * 批量添加消息ID到已删除列表
 */
export async function addDeletedMessageIds(
  messageIds: string[],
  currentUserId: Ref<string | null>
): Promise<void> {
  const deletedIds = await getDeletedMessageIds(currentUserId);
  messageIds.forEach(id => deletedIds.add(id));
  await saveDeletedMessageIds(deletedIds, currentUserId);
}

/**
 * 获取消息存储键名
 */
export async function getMessagesStorageKey(currentUserId: Ref<string | null>): Promise<string> {
  let userId = isTauri()
    ? await storageGet('openId')
    : localStorage.getItem('openId');
  
  if (!userId && currentUserId.value) {
    userId = currentUserId.value;
  }
  
  if (!userId) {
    throw new Error('无法获取当前用户的 open_id，请先登录后再读取消息缓存');
  }
  
  return `chat_messages_${userId}`;
}

/**
 * 保存消息到安全存储
 */
export async function saveMessagesToStorage(messages: Ref<Message[]>) {
  try {
    const messageCountBeforeSave = messages.value.length;
    
    if (messageCountBeforeSave === 0) {
      console.warn('⚠️ 保存消息时，内存中的消息列表为空，跳过保存');
      return;
    }
    
    const currentOpenId = isTauri()
      ? await storageGet('openId')
      : localStorage.getItem('openId');
    
    if (!currentOpenId) {
      console.warn('⚠️ 无法获取当前用户的 open_id，跳过保存消息');
      return;
    }
    
    const storageKey = `chat_messages_${currentOpenId}`;
    
    if (messages.value.length === 0) {
      console.warn('⚠️ 保存消息时，消息列表在获取 open_id 后被清空，跳过保存');
      return;
    }
    
    const value = JSON.stringify(messages.value);
    const dataSize = value.length;
    const dataSizeKB = (dataSize / 1024).toFixed(2);
    
    let parsedMessages: any[] = [];
    try {
      parsedMessages = JSON.parse(value);
      if (!Array.isArray(parsedMessages)) {
        console.error('❌ 保存的消息不是数组格式:', typeof parsedMessages);
        return;
      }
    } catch (e) {
      console.error('❌ 消息序列化失败:', e);
      return;
    }
    
    console.log('💾 准备保存消息到存储:', {
      storageKey,
      currentOpenId,
      messageCount: parsedMessages.length,
      dataSize: `${dataSize} 字节 (${dataSizeKB} KB)`,
      sampleMessageIds: parsedMessages.slice(0, 3).map(m => m.message_id)
    });
    
    if (isTauri()) {
      await storageSet(storageKey, value);
      console.log('💾 [前端] 消息已保存到 Tauri 安全存储（仅当前用户）:', {
        storageKey,
        currentOpenId,
        messageCount: messages.value.length,
        dataSize: `${dataSize} 字节 (${dataSizeKB} KB)`,
      });
    } else {
      localStorage.setItem(storageKey, value);
      console.log('💾 [前端] 消息已保存到 localStorage（仅当前用户）:', {
        storageKey,
        currentOpenId,
        messageCount: messages.value.length,
        dataSize: `${dataSize} 字节 (${dataSizeKB} KB)`,
        location: '浏览器 localStorage',
      });
    }
  } catch (error) {
    console.error('❌ 保存消息失败:', error);
  }
}

/**
 * 从安全存储恢复消息
 */
export async function loadMessagesFromStorage(
  messages: Ref<Message[]>,
  currentUserId: Ref<string | null>
): Promise<void> {
  try {
    const currentOpenId = isTauri()
      ? await storageGet('openId')
      : localStorage.getItem('openId');
    
    if (!currentOpenId) {
      console.warn('⚠️ 无法获取当前用户的 open_id，跳过读取消息缓存');
      return;
    }
    
    const storageKey = `chat_messages_${currentOpenId}`;
    
    console.log('📖 [前端] 开始从缓存加载历史消息（仅当前用户）:', {
      storageKey,
      currentOpenId,
      location: isTauri() ? 'Tauri 安全存储' : '浏览器 localStorage',
    });
    
    const saved = await storageGet(storageKey);
    if (saved) {
      const parsed = JSON.parse(saved);
      const rawMessageCount = Array.isArray(parsed) ? parsed.length : 0;
      
      console.log('📖 [前端] 从缓存读取到原始数据:', {
        storageKey,
        rawMessageCount,
        dataSize: `${saved.length} 字节 (${(saved.length / 1024).toFixed(2)} KB)`
      });
      
      // 过滤掉通话邀请消息（message_content_type === 4）
      // 通话邀请是实时消息，不应该显示在聊天界面
      const filteredMessages = parsed.filter((msg: Message) => {
        const messageContentType = (msg as any)?.message_content_type;
        if (messageContentType === 4) {
          console.log('📖 [前端] 从历史消息中过滤掉通话邀请消息:', {
            message_id: msg.message_id,
            message_content_type: messageContentType,
          });
          return false; // 过滤掉通话邀请消息
        }
        return true; // 保留其他消息
      });
      
      console.log('📖 [前端] 过滤通话邀请消息后:', {
        originalCount: parsed.length,
        filteredCount: filteredMessages.length,
        removedCount: parsed.length - filteredMessages.length,
      });
      
      // 确保所有消息的 ID 格式一致
      const messagesWithIds = filteredMessages.map((msg: Message) => ({
        ...msg,
        from_user_id: String(msg.from_user_id || ''),
        to_user_id: String(msg.to_user_id || ''),
      }));
      
      // 收集需要转换的雪花ID
      const snowflakeIdsToConvert = new Set<string>();
      messagesWithIds.forEach((msg: Message) => {
        if (msg.isReceived && /^\d+$/.test(msg.from_user_id)) {
          snowflakeIdsToConvert.add(msg.from_user_id);
        }
        if (!msg.isReceived && /^\d+$/.test(msg.to_user_id)) {
          snowflakeIdsToConvert.add(msg.to_user_id);
        }
        if (!msg.isReceived && /^\d+$/.test(msg.from_user_id)) {
          snowflakeIdsToConvert.add(msg.from_user_id);
        }
      });
      
      // 批量转换雪花ID，同时保存用户名和open_id的映射
      // 使用双向映射：snowflakeId -> { name, open_id }
      const idToUserInfoMap = new Map<string, { name?: string; open_id?: string }>();
      
      const currentUserStr = isTauri() 
        ? (await storageGet('user')) || '{}'
        : localStorage.getItem('user') || '{}';
      const currentUser = JSON.parse(currentUserStr);
      const currentOpenIdForMap = isTauri()
        ? await storageGet('openId')
        : localStorage.getItem('openId');
      if (currentUser.name && currentOpenIdForMap) {
        idToUserInfoMap.set(String(currentOpenIdForMap), { 
          name: currentUser.name, 
          open_id: currentOpenIdForMap 
        });
        if (currentUser.name !== currentOpenIdForMap) {
          idToUserInfoMap.set(currentUser.name, { 
            name: currentUser.name, 
            open_id: currentOpenIdForMap 
          });
        }
      }
      
      if (snowflakeIdsToConvert.size > 0) {
        console.log('📖 [前端] 需要转换的雪花ID数量:', snowflakeIdsToConvert.size);
        const { getUser } = await import('../services/message');
        await Promise.all(Array.from(snowflakeIdsToConvert).map(async (snowflakeId) => {
          try {
            const user = await getUser(snowflakeId);
            if (user) {
              const userInfo: { name?: string; open_id?: string } = {};
              if (user.name) userInfo.name = user.name;
              if (user.open_id) userInfo.open_id = user.open_id;
              
              // 保存雪花ID到用户信息的映射
              idToUserInfoMap.set(snowflakeId, userInfo);
              
              // 同时保存用户名和open_id的映射（如果存在）
              if (user.name && user.name !== snowflakeId) {
                const existing = idToUserInfoMap.get(user.name) || {};
                idToUserInfoMap.set(user.name, { ...existing, ...userInfo });
              }
              if (user.open_id && user.open_id !== snowflakeId) {
                const existing = idToUserInfoMap.get(user.open_id) || {};
                idToUserInfoMap.set(user.open_id, { ...existing, ...userInfo });
              }
            }
          } catch (e: any) {
            if (!e.message || !e.message.includes('不存在')) {
              console.log('无法转换雪花ID为用户名:', snowflakeId, e);
            }
          }
        }));
      }
      
      // 应用转换：优先使用open_id，如果没有则使用用户名
      const convertedMessages = messagesWithIds.map((msg: Message) => {
        let fromUserId = msg.from_user_id;
        let toUserId = msg.to_user_id;
        
        // 转换from_user_id
        if (/^\d+$/.test(fromUserId)) {
          const userInfo = idToUserInfoMap.get(fromUserId);
          if (userInfo) {
            // 优先使用open_id，如果没有则使用用户名
            fromUserId = userInfo.open_id || userInfo.name || fromUserId;
          }
        }
        
        // 转换to_user_id
        if (/^\d+$/.test(toUserId)) {
          const userInfo = idToUserInfoMap.get(toUserId);
          if (userInfo) {
            // 优先使用open_id，如果没有则使用用户名
            toUserId = userInfo.open_id || userInfo.name || toUserId;
          }
        }
        
        // 确保旧消息也有 chat_type
        let chatType = msg.chat_type;
        if (chatType === undefined || chatType === null) {
          try {
            const groupsStr = localStorage.getItem('groups') || '[]';
            const groups = JSON.parse(groupsStr);
            const toId = String(toUserId || '').trim();
            
            const isInGroupList = groups.some((g: any) => {
              const group = g.group || g;
              const groupId = String(group.group_id || '');
              const normalizedGroupId = groupId.replace(/^group_/i, '').toLowerCase();
              const normalizedToId = toId.replace(/^group_/i, '').toLowerCase();
              return normalizedGroupId === normalizedToId || groupId === toId;
            });
            
            chatType = isInGroupList ? 2 : 1;
          } catch (e) {
            chatType = 1;
          }
        }
        
        return {
          ...msg,
          from_user_id: fromUserId,
          to_user_id: toUserId,
          chat_type: chatType,
        };
      });
      
      // 合并消息，去重
      const newMessages: Message[] = [];
      const duplicateCount = { byId: 0, byContent: 0 };
      
      for (const msg of convertedMessages) {
        const existingById = messages.value.find(m => String(m.message_id) === String(msg.message_id));
        if (existingById) {
          duplicateCount.byId++;
          continue;
        }
        
        // 检查基于内容和时间戳的重复
        const existingByContent = messages.value.find(m => {
          const existingChatType = m.chat_type;
          const incomingChatType = msg.chat_type;
          if (existingChatType !== undefined && incomingChatType !== undefined && existingChatType !== incomingChatType) {
            return false;
          }
          
          const existingTimestamp = m.timestamp_ms || m.timestamp || 0;
          const incomingTimestamp = msg.timestamp_ms || msg.timestamp || 0;
          const timeDiff = Math.abs(existingTimestamp - incomingTimestamp);
          if (timeDiff > 5000) {
            return false;
          }
          
          // 群组消息检查
          if (incomingChatType === 2 && existingChatType === 2) {
            const existingToId = String(m.to_user_id || '').replace(/^group_/i, '').toLowerCase();
            const incomingToId = String(msg.to_user_id || '').replace(/^group_/i, '').toLowerCase();
            if (existingToId !== incomingToId) {
              return false;
            }
            
            const existingFromId = String(m.from_user_id || '').trim();
            const incomingFromId = String(msg.from_user_id || '').trim();
            if (existingFromId !== incomingFromId) {
              return false;
            }
            
            const existingContent = String(m.message || '').replace(/\s+/g, '').trim();
            const incomingContent = String(msg.message || '').replace(/\s+/g, '').trim();
            const existingFileUrl = String(m.file_url || '').trim();
            const incomingFileUrl = String(msg.file_url || '').trim();
            
            if (existingFileUrl && incomingFileUrl) {
              return existingFileUrl === incomingFileUrl || 
                     existingFileUrl.toLowerCase().includes(incomingFileUrl.toLowerCase()) ||
                     incomingFileUrl.toLowerCase().includes(existingFileUrl.toLowerCase());
            } else if (!existingFileUrl && !incomingFileUrl) {
              return existingContent === incomingContent;
            }
            return false;
          }
          
          // 个人消息检查
          if ((incomingChatType === 1 || incomingChatType === undefined) && 
              (existingChatType === 1 || existingChatType === undefined)) {
            const existingFromId = String(m.from_user_id || '').trim();
            const incomingFromId = String(msg.from_user_id || '').trim();
            const existingToId = String(m.to_user_id || '').trim();
            const incomingToId = String(msg.to_user_id || '').trim();
            
            if (existingFromId !== incomingFromId || existingToId !== incomingToId) {
              return false;
            }
            
            const existingContent = String(m.message || '').replace(/\s+/g, '').trim();
            const incomingContent = String(msg.message || '').replace(/\s+/g, '').trim();
            const existingFileUrl = String(m.file_url || '').trim();
            const incomingFileUrl = String(msg.file_url || '').trim();
            
            if (existingFileUrl && incomingFileUrl) {
              return existingFileUrl === incomingFileUrl || 
                     existingFileUrl.toLowerCase().includes(incomingFileUrl.toLowerCase()) ||
                     incomingFileUrl.toLowerCase().includes(existingFileUrl.toLowerCase());
            } else if (!existingFileUrl && !incomingFileUrl) {
              return existingContent === incomingContent;
            }
            return false;
          }
          
          return false;
        });
        
        if (existingByContent) {
          duplicateCount.byContent++;
          continue;
        }
        
        newMessages.push(msg);
      }
      
      if (newMessages.length > 0) {
        messages.value = [...messages.value, ...newMessages].sort((a, b) => 
          (a.timestamp_ms || a.timestamp) - (b.timestamp_ms || b.timestamp)
        );
        
        console.log('✅ [前端] 历史消息加载完成（合并模式）:', {
          storageKey,
          existingMessages: messages.value.length - newMessages.length,
          newMessagesFromCache: newMessages.length,
          duplicateById: duplicateCount.byId,
          duplicateByContent: duplicateCount.byContent,
          totalMessages: messages.value.length,
        });
      } else {
        if (messages.value.length > 0) {
          console.log('📖 [前端] 缓存中没有新消息，保留内存中的消息:', {
            storageKey,
            memoryMessages: messages.value.length,
            cacheMessages: convertedMessages.length,
          });
        } else {
          messages.value = convertedMessages;
          
        console.log('✅ [前端] 历史消息加载完成（直接加载）:', {
          storageKey,
          totalMessages: messages.value.length,
          sampleMessageIds: messages.value.slice(0, 5).map(m => ({
            message_id: m.message_id,
            from_user_id: m.from_user_id,
            to_user_id: m.to_user_id,
            isReceived: m.isReceived,
            chat_type: m.chat_type,
          })),
        });
        }
      }
    } else {
      console.log('📖 [前端] 未找到历史消息缓存:', {
        storageKey,
        location: isTauri() ? 'Tauri 安全存储' : '浏览器 localStorage',
      });
    }
  } catch (error) {
    console.error('❌ [前端] 从缓存恢复消息失败:', {
      error,
      storageKey: await getMessagesStorageKey(currentUserId).catch(() => 'unknown'),
    });
  }
}

